home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9247 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: newsfeeds.ans.net!btco!newsadm
  2. From: Shalom Reich <sqr1874@acf4.nyu.edu>
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: Thu, 29 Feb 1996 09:42:43 -0500
  6. Organization: Bankers Trust Company
  7. Message-ID: <3135BB63.4459@acf4.nyu.edu>
  8. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>
  9. NNTP-Posting-Host: algsvw0058.btco.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB1 (WinNT; I)
  14.  
  15. Boris Burtin wrote:
  16. > I have noticed that a copy constructor and operator= perform pretty
  17. > much the same function.  The code I wrote for my class simply copies
  18. > each member variable from one class to the other.
  19. > First - if all you are doing in a copy ctor and operator= is copying
  20. members (i.e. bitwise copy) the compiler will construct these two 
  21. functions for you.
  22.  
  23. The main purpose of these functions should be to implement the 
  24. *semantics* of copying when all of the data needed by an object
  25. of the class is not contained in the members.  One *usually* needs
  26. to define these functions when one or more members are *pointers* 
  27. to additional data that is part of the class semantics.
  28.  
  29. Second - once one or more of the members ar pointers, the operator=
  30. needs to consider (a) assignment to self (b) cleaning up what was
  31. originally pointed to by the member of "this".
  32.  
  33. Third - it is always preferable to initialize members in the any ctor
  34. (including the copy ctor) with the initialization list rather than with
  35. code in the body of the ctor.
  36.  
  37. A good book that covers these issues (in a very readable style) is
  38. "Effective C++" by Scott Meyer.  Addison-Wesley.
  39.  
  40. Shalom Reich
  41.